package com.hummingbird.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hummingbird.portal.dto.AnswerDTO;
import com.hummingbird.portal.exception.ServiceException;
import com.hummingbird.portal.mapper.UserMapper;
import com.hummingbird.portal.pojo.Answer;
import com.hummingbird.portal.mapper.AnswerMapper;
import com.hummingbird.portal.pojo.User;
import com.hummingbird.portal.service.IAnswerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author -1E18
 * @since 2024-09-22
 */
@Service
@Slf4j
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer> implements IAnswerService {
    // 属性、 构造器、 set方法
    @Resource
    private AnswerMapper answerMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    @Transactional  // 返回的是同一个对象
    public Answer saveAnswer(AnswerDTO answerDTO, String username) {
        User user = userMapper.findUserByUsername(username);
        Answer answer = new Answer()
                .setQuestId(answerDTO.getQuestionId())
                .setContent(answerDTO.getContent())
                .setUserId(user.getId())
                .setUserNickName(user.getNickname())
                .setAcceptStatus(0)
                .setLikeCount(0)
                .setCreatetime(LocalDateTime.now());
        int num = answerMapper.insert(answer);
        if (num != 1) {
            throw ServiceException.busy();
        }
        log.info("answer: {}", answer);
        return answer;
    }

    @Override
    public List<Answer> getAnswersByQuestionId(Integer questionId) {
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("quest_id", questionId);

        List<Answer> answers = answerMapper.selectList(queryWrapper);
        return answers;
    }
}
